{{set . "title" "Chat room"}}
{{template "header.html" .}}

<h1>WebSocket — You are now chatting as {{.user}}
  <a href="/">Leave the chat room</a></h1>

<div id="thread">
  <script type="text/html" id="message_tmpl">
    <% if(event.Type == 'message') { %>
      <div class="message <%= event.User == '{{.user}}' ? 'you' : '' %>">
        <h2><%= event.User %></h2>
        <p>
          <%= event.Text %>
        </p>
      </div>
    <% } %>
    <% if(event.Type == 'join') { %>
      <div class="message notice">
        <h2></h2>
        <p>
          <%= event.User %> joined the room
        </p>
      </div>
    <% } %>
    <% if(event.Type == 'leave') { %>
      <div class="message notice">
        <h2></h2>
        <p>
          <%= event.User %> left the room
        </p>
      </div>
    <% } %>
    <% if(event.Type == 'quit') { %>
      <div class="message important">
        <h2></h2>
        <p>
          You are now disconnected!
        </p>
      </div>
    <% } %>
  </script>
</div>

<div id="newMessage">
  <input type="text" id="message" autocomplete="off" autofocus>
  <input type="submit" value="send" id="send">
</div>

<script type="text/javascript">

  // Create a socket
  var socket = new WebSocket('ws://'+window.location.host+'/websocket/room/socket?user={{.user}}')

  // Display a message
  var display = function(event) {
    $('#thread').append(tmpl('message_tmpl', {event: event}));
    $('#thread').scrollTo('max')
  }

  // Message received on the socket
  socket.onmessage = function(event) {
    display(JSON.parse(event.data))
  }

  $('#send').click(function(e) {
    var message = $('#message').val()
    $('#message').val('')
    socket.send(message)
  });

  $('#message').keypress(function(e) {
    if(e.charCode == 13 || e.keyCode == 13) {
      $('#send').click()
      e.preventDefault()
    }
  })

</script>
